package com.tloss.stdao.service;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.tloss.Constants;
import com.tloss.stdao.JPAResourceBean;
import com.tloss.stdao.Profit;

public class ProfitService {
	public Profit select(String username) {
		Profit profit = new Profit();
		EntityManager em = JPAResourceBean.getEMF().createEntityManager();
		Query q = em
				.createQuery("select SUM(t.value*t.quality) from StockHistory t where t.username=?1 and t.transactionType=?2");
		q.setParameter(1, username);
		q.setParameter(2, Constants.BUY);
		int sumBuy = ((Number) q.getSingleResult()).intValue();
		q = em.createQuery("select SUM(t.value*t.quality) from StockHistory t where t.username=?1 and t.transactionType=?2");
		q.setParameter(1, username);
		q.setParameter(2, Constants.SELL);
		int sumSell = ((Number) q.getSingleResult()).intValue();
		profit.setSumBuy(sumBuy);
		profit.setSumSell(sumSell);
		profit.setTotal(sumSell - sumBuy);
		em.close();
		return profit;
	}
}
